﻿using FlyHorse.LIMS.DALFactory;
using FlyHorse.LIMS.IDAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlyHorse.LIMS.Model;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

namespace FlyHorse.LIMS.BLL
{
    public abstract class BaseBll<T> where T : class,new()
    {
        public IDBSession CurrentDBSession
        {
            get
            {
                // return new DBSession();//暂时
                return DBSessionFactory.CreateDBSession();
            }
        }

        

        public IDAL.IBaseDal<T> CurrentDal { get; set; }
        public abstract void SetCurrentDal();
        public BaseBll()
        {
            SetCurrentDal();//子类一定要实现抽象方法。
        }
        public IQueryable<T> LoadEntities(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda)
        {
            return CurrentDal.LoadEntitiesAsNoTracking(whereLambda);
        }

        public IQueryable<T> LoadEntitiesAsNoTracking(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda)
        {
            return CurrentDal.LoadEntitiesAsNoTracking(whereLambda);
        }

        public T FindEntity(string id)
        {
            return this.CurrentDBSession.Db.Set<T>().Find(id);
        }

        public IQueryable<T> LoadPageEntities<s>(int pageIndex, int pageSize, out int totalCount, System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, s>> orderbyLambda, bool isAsc)
        {
            return CurrentDal.LoadPageEntities<s>(pageIndex, pageSize, out totalCount, whereLambda, orderbyLambda, isAsc);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool DeleteEntity(T entity)
        {
            CurrentDal.DeleteEntity(entity);
            return CurrentDBSession.SaveChanges();
        }
        /// <summary>
        ///  用新的DbContext 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool EditEntity(T entity)
        {
            this.CurrentDBSession.Db.Set<T>().Remove(entity);
            return CurrentDBSession.SaveChanges();
        }


        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public T AddEntity(T entity)
        {
            CurrentDal.AddEntity(entity);
            bool res = CurrentDBSession.SaveChanges();
            if (res)
            {
                return entity;
            }
            else
            {
                return null;
            }
        }
    }
}
